import { watch } from 'vue';
import { useGlobalStore } from '@common/store/global-store';
import { loadPlanConfig } from '@/data/api/setting';
import { useAdminStore } from '@/stores/admin-store';
import { useMenuStore } from '@/stores/menu-store';
import { toggleTheme } from '@common/helper/theme';
import { toBoolean, decode, getFileUrlByKey, getAjaxBaseURL } from '@jecloud/utils';
import { useUserConfigStore } from '@/stores/user-config-store';
/**
 * 方案
 * @returns
 */
export function usePlan() {
  const globalStore = useGlobalStore();
  const adminStore = useAdminStore();
  // 监听方案，修改系统配置
  const watchActivePlan = function () {
    watch(
      () => globalStore.activePlan,
      (plan) => {
        let configPromise = null;
        if (globalStore.plans.has(plan)) {
          configPromise = Promise.resolve(globalStore.plans.get(plan));
        } else {
          configPromise = loadPlanConfig(plan).then((config) => {
            globalStore.plans.set(plan, config);
            return config;
          });
        }
        configPromise?.then((config) => {
          changePlanConfig(config);
          adminStore.emitMicroAll('admin-plan-change', config);
        });
      },
      { immediate: true },
    );
  };
  return { watchActivePlan };
}
/**
 * 切换方案配置
 * @param {*} config
 */
function changePlanConfig(config) {
  const menuStore = useMenuStore();
  const globalStore = useGlobalStore();
  // 主题设置
  const grayMode = toBoolean(config.JE_SYS_GRAY_MODEL); // 灰度模式
  toggleTheme('grayMode', grayMode);

  // 菜单设置
  menuStore.topMenuAlign = config.JE_SYS_TOPMENU || menuStore.topMenuAlign; // 顶部菜单位置
  menuStore.setTopMenuLogo(config.JE_SYS_WEBLOGO, true); // 系统logo对象

  // 系统设置
  document.title = config.JE_SYS_WEBTITLE; // 系统标题
  const titleIcon = document.querySelector('link[rel="icon"]');
  if (titleIcon) {
    titleIcon.href = `${getAjaxBaseURL()}/je/meta/settingPlan/getPicture?code=${
      globalStore.activePlan
    }&type=browserIcon`;
  }
}

/**
 * 切换用户态配置
 */
export function changeUserConfig() {
  const userConfigStore = useUserConfigStore();
  const globalStore = useGlobalStore();
  // 主题设置
  const systemTheme =
    userConfigStore.systemTheme || globalStore.getPlanConfig('JE_SYS_DEFAULT_HUE'); // 系统主题
  const siderTheme =
    userConfigStore.siderTheme || globalStore.getPlanConfig('JE_SYS_DEFAULT_MENUCOLOR'); // 菜单主题
  systemTheme && toggleTheme('systemTheme', systemTheme);
  siderTheme && toggleTheme('siderTheme', siderTheme);
}
